package com.zhengtoon.mctoon.conv.service;

import com.alibaba.fastjson.JSON;
import com.bjtoon.framework.sdk.toon.tooncode.ToonCodeInfo;
import com.bjtoon.framework.utils.redis.RedisCacheService;
import com.google.common.collect.Maps;
import com.zhengtoon.mctoon.conv.bean.session.OrgSessionInfo;
import com.zhengtoon.mctoon.conv.service.ISessionService;
import com.zhengtoon.mctoon.conv.utils.*;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.UUID;

/**
 * session 服务
 *
 * @author 144637
 */
@Service
public class SessionServiceImpl implements ISessionService {

    private static Logger log = LoggerFactory.getLogger(ConvPraiseInfoServiceImpl.class);

    @Autowired
    private RedisCacheService redisCacheService;


    // session 过期时间(分钟)
    private final static Long SESSION_EXPIRED_MINUTES = Long
            .valueOf(SysConfig.getPropertyValue("config.session_expired_minutes"));

    /**
     * 根据 sessionId 获取 sessionInfo 信息
     *
     * @param sessionId sessionId
     * @return SessionInfo
     * 144637
     */
    @Override
    public SessionInfo getSessionInfo(String sessionId) {
        String sessionKey = getSessionKey(sessionId);
        String sessionInfoValue = redisCacheService.getRedisCacheByKey(sessionKey);
        if (StringUtils.isNotBlank(sessionInfoValue)) {

            SessionInfo sessionInfo = JSON.parseObject(sessionInfoValue, SessionInfo.class);

            // 会话续期
            redisCacheService.setRedisCacheByKey(sessionKey, sessionInfoValue, SESSION_EXPIRED_MINUTES, AppConstant.CONV_REDIS_CACHE_TIME_UNIT);

            return sessionInfo;
        } else {
            return null;
        }
    }

    /**
     * 通过toonCode 解析信息获取用户的sesssionId
     *
     * @param BjtCodeInfo toonCode中解析出来的对象
     * @return String sessionId
     */
    public String querySessionIdByToonCode(ToonCodeInfo BjtCodeInfo) {
        SessionInfo sessionInfo = convertToSessionInfo(BjtCodeInfo);
        return saveSessionInfo(sessionInfo);
    }


    /**
     * 将 BjtCodeInfo 对象转换为 SessionInfo 对象
     *
     * @param BjtCodeInfo BjtCodeInfo对象
     * @return SessionInfo
     */
    private SessionInfo convertToSessionInfo(ToonCodeInfo BjtCodeInfo) {
        SessionInfo sInfo = new SessionInfo();
        sInfo.setUserId(BjtCodeInfo.getUserId());
        sInfo.setCertKey(BjtCodeInfo.getKey());
        sInfo.setToonNo(BjtCodeInfo.getToonNo());
        return sInfo;
    }

    /**
     * 保存sessionInfo 并返回sessionId   144637
     *
     * @param sessionInfo sessionInfo
     * @return String sessionId
     */
    private String saveSessionInfo(SessionInfo sessionInfo) {

        String userId = sessionInfo.getUserId();
        // 判断是否存在Session
        String userKey = getUserSessionKey(userId);

        // 删除已经存在的session会话
        String sessionId = redisCacheService.getRedisCacheByKey(userKey);
        if (StringUtils.isNotBlank(sessionId)) {
            String sessionKey = getSessionKey(sessionId);
            redisCacheService.deleteRedisCacheByKey(sessionKey);
        }

        // 1.获取原有 session 信息
        SessionInfo sInfo = new SessionInfo();
        sInfo.setUserId(sessionInfo.getUserId());
        sInfo.setCertKey(sessionInfo.getCertKey());
        sInfo.setToonNo(sessionInfo.getToonNo());

        String sessionInfoJson = JSON.toJSONString(sInfo);

        // 生成sessionId
        String newSessionId = UUID.randomUUID().toString();
        String sessionKeyNew = getSessionKey(newSessionId);

        // 设置sessionInfo

        redisCacheService.setRedisCacheByKey(sessionKeyNew, sessionInfoJson, SESSION_EXPIRED_MINUTES, AppConstant.CONV_REDIS_CACHE_TIME_UNIT);

        // 用户key设置
        redisCacheService.setRedisCacheByKey(userKey, newSessionId, SESSION_EXPIRED_MINUTES, AppConstant.CONV_REDIS_CACHE_TIME_UNIT);

        return newSessionId;

    }

    /**
     * 记录toonNo-->redis中保存的userSessionkey   144637
     *
     * @param userId 北京通号
     * @return String
     */
    private String getUserSessionKey(String userId) {
        return AppConstant.CONV_USER_PREFIX + userId;
    }

    /**
     * 根据sessionId 获取sessionkey 144637
     *
     * @param sessionId sessionId
     * @return String
     */
    private String getSessionKey(String sessionId) {
        return AppConstant.CONV_SESSION_PREFIX + sessionId;
    }

}
